<template>
  <div>
    <Modal v-model="model" :title="isAdd ? '新增台账字段' : '编辑台账字段'" :closable="false" :mask-closable="false">

      <template v-slot:footer>
        <div class="footer">
          <div style="flex: 1;" />
          <Button type="text" @click='onCancel'>取消</Button>
          <Button type="primary" @click='onOK'>确定</Button>
        </div>
      </template>

      <Form ref='edit' :model='info' :rules='rules' :label-width="80" @submit.native.prevent>
        <FormItem label="字段名称" prop="fieldValue">
          <Input type="text" v-model="info.fieldValue" :disabled='!canEditTitle'></Input>
          <!-- <Input type="text" v-model="info.fieldValue"></Input> -->
        </FormItem>
        <FormItem label="是否必填" prop="ifRequired">
          <RadioGroup v-model="info.ifRequired">
            <Radio :label="1">是</Radio>
            <Radio :label="2">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="信息分类" prop="infoType">
          <Select v-model="info.infoType">
            <Option v-for="(item) in types" :key='item.key' :value="item.type">{{item.title}}</Option>
          </Select>
        </FormItem>
        <FormItem label="类型" prop="inputType">
          <RadioGroup v-model="info.inputType">
            <Radio :label="2" :disabled='!isAdd'>单选</Radio>
            <Radio :label="3" :disabled='!isAdd'>多选</Radio>
            <Radio :label="1" :disabled='!isAdd'>填空</Radio>
          </RadioGroup>
        </FormItem>
      </Form>
      <Form v-if="info.inputType != 1" ref='option' :model='option' :label-width="80">
        <FormItem label="选项内容" />
        <FormItem v-for="(item) in optionNum" :key="item" :label="'选项 ' + item" :prop="'key'+item" :rules="rules.item">
          <Row>
            <Col span="18">
            <Input type="text" v-model="option['key'+item]"></Input>
            </Col>
            <Col span="4" offset="1">
            <Button v-if="item>2" type='error' @click="onRemoveOption('key'+item)">删除</Button>
            </Col>
          </Row>
        </FormItem>
        <FormItem>
          <Row>
            <Col span="12">
            <Button type="dashed" long @click="onAddOption" icon="md-add">添加选项值</Button>
            </Col>
          </Row>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
  import fieldMgr from './field.js'

  export default {
    data() {
      return {
        model: false,
        isAdd: false,

        info: {},
        option: {},
        optIds: {},
        optionNum: 2,
        types: fieldMgr.infoTypes(),
        
        field: null,

        rules: {
          fieldValue: [{
            required: true,
            message: '请输入字段名称',
            trigger: 'blur'
          }, {
            max: 10,
            message: '最多10个字',
            trigger: 'blur,change'
          }],
          item: [{
            required: true,
            message: '请输入选项内容',
            trigger: 'blur'
          }, {
            max: 20,
            message: '最多20个字',
            trigger: 'blur,change'
          }]
        },

        isEdit: false,
        canEdit: false,
        canEditTitle: false,
      }
    },
    watch: {
      info: {
        handler(n) {
          if (this.canEdit) {
            this.isEdit = true
          }
        },
        deep: true
      },
      option: {
        handler(n) {
          if (this.canEdit) {
            this.isEdit = true
          }
        },
        deep: true
      }
    },
    methods: {
      showEdit(field, data) {
        
        if (this.$refs.edit) {
          this.$refs.edit.resetFields()
        }
        if (this.$refs.option) {
          this.$refs.option.resetFields()
        }
        
        this.field = field
        this.canEdit = false
        this.isEdit = false
        this.optionNum = 2
        
        if (data) {
          let dbkeys = ['intention_purpose', 'intention_product', 'intention_house_type', 'intention_area', 'intention_total_price', 'intention_average_price']
          this.canEditTitle = dbkeys.indexOf(data.dbKey) < 0
          this.info = {
            ...data
          }
          this.option = {}
          if (data.options) {
            this.optionNum = this.info.options.length || 2
            this.info.options.forEach((item, idx) => {
              this.option['key' + (idx + 1)] = item.optionValue
              this.optIds['key' + (idx + 1)] = item.optionId
              this.option = {...this.option}
            })
          }
        } else {
          this.canEditTitle = true
          this.info = {
            ifRequired: 1,
            infoType: 1,
            inputType: 2
          }
          this.option = {}
        }
        this.isAdd = !data
        this.model = true
        this.$nextTick(() => {
          this.canEdit = true
        })
      },
      onAddOption() {
        this.optionNum++
      },
      onRemoveOption(key) {
        let ki = 1
        let opt = {}
        let optIds = {}
        this.field.deleteOption(this.optIds[key])
        for (let i = 0; i < this.optionNum; i++) {
          let k = 'key' + ki
          let ok = 'key' + (i + 1)
          if (ok != key) {
            opt[k] = this.option[ok]
            optIds[k] = this.optIds[ok]
            ki++
          }
        }
        this.optionNum--
        this.option = opt
        this.optIds = optIds
      },
      onOK() {
        let ps = [this.$refs.edit.validate()]
        if (this.info.inputType != 1) {
          ps.push(this.$refs.option.validate())
          let key = this.isAdd ? 'optionReqList' : 'options'
          this.info[key] = Object.keys(this.option).map(k => {
            let data = {
              optionValue: this.option[k]
            }
            if (this.optIds[k]) {
              data.optionId = this.optIds[k]
            }
            return data
          })
        }
        Promise.all(ps).then(res => {
          if (res.indexOf(false) < 0) {
            if (this.field.hasFieldValue(this.info)) {
              this.$Message.error('字段名称已存在')
            } else if (this.isAdd) {
              this.info.styleType = this.info.inputType == 1 ? 1: 2// 新增处理单选多选多行平铺
              this.field.addItem(this.info).then(res => {
                this.$emit('add', res)
                this.model = false
              }).catch(err => {
                this.$Message.error(err)
              })
            } else {
              this.$emit('edit', {...this.info})
              this.model = false
            }
          }
        })
      },
      onCancel() {
        if (this.isEdit) {
          this.$Modal.confirm({
            title: '是否确认取消自定义台账字段' + (this.isAdd ? '添加？' : '编辑？'),
            onOk: () => {
              this.model = false
            }
          });
        } else {
          this.model = false
        }
      }
    }
  }
</script>

<style lang='scss' scoped>
  .footer {
    display: flex;
  }
</style>
